from app.aoduo_admin.models import AdminAccount, AdminAccountPassword
from rest_framework.views import APIView
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from common.authCheck.adminAuth import check_admin_login
from .chiefAdminAuthVerify import chiefAdminCheck
import json


class AdminInfoView(APIView):

    @check_admin_login
    @chiefAdminCheck
    def post(self, request):
        """
        新增管理员
        :param request:
        :return:
        """
        try:
            jsonParams = json.loads((request.body).decode('utf-8'))
            # 检查参数合法性
            if jsonParams.get('username') is None:
                return JsonResponse({
                    'status': False,
                    'errMsg': '用户名不能为空'
                }, status=401)
            if jsonParams.get('email') is None:
                return JsonResponse({
                    'status': False,
                    'errMsg': '邮箱不能为空'
                }, status=401)
            #
            newPassword = AdminAccountPassword.objects.create(password=make_password(jsonParams.get('password')))
            newAdmin = AdminAccount.objects.create(
                username=jsonParams.get('username'),
                email=jsonParams.get('email'),
                password=newPassword,
                admin_type=jsonParams.get('type')
            )
            return JsonResponse({
                'status': True,
                'id': newAdmin.id,
                'username': newAdmin.username,
                'email': newAdmin.email
            })
        except Exception as ex:
            return JsonResponse({
                'status': False,
                'errMsg': str(ex)
            }, status=403)

    @check_admin_login
    @chiefAdminCheck
    def delete(self, request, adminID):
        """
        禁用管理员账户
        :param request:
        :param adminID:
        :return:
        """
        infoAdmin = AdminAccount.objects.filter(id=adminID)
        if not infoAdmin.exists():
            return JsonResponse({
                'status': False,
                'errMsg': '管理员账户不存在'
            }, status=404)
        infoAdmin = infoAdmin[0]
        infoAdmin.active = False
        return JsonResponse({
            'status': True,
            'id': infoAdmin.id
        })
